package cn.cqie.attendance.common.util;

import cn.cqie.attendance.common.pojo.User;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 本地缓存token
 */
public class LocalJwt {

    private static final ExpiringMap<String, User> localUser = ExpiringMap.builder()
            .maxSize(3000)
            .expiration(30, TimeUnit.MINUTES)
            .expirationPolicy(ExpirationPolicy.ACCESSED)
            .variableExpiration()
            .build();
    private static final ExpiringMap<String, String> localCode = ExpiringMap.builder()
            .maxSize(5000)
            .expiration(2, TimeUnit.MINUTES)
            .expirationPolicy(ExpirationPolicy.ACCESSED)
            .variableExpiration()
            .build();

    public static void setCurrentUser(HttpServletRequest request, User user) {
        localUser.put(getToken(request), user);
        printUser(getToken(request));
    }

    public static String getCode(String tag) {
        if (StringUtils.isEmpty(tag)) {
            return UUID.randomUUID().toString();
        }
        return localCode.get(tag);
    }

    public static void setCode(String tag, String code) {
        localCode.put(tag, code);
        printCode(tag);
    }

    public static void removeCode(String uuid) {
        localCode.remove(uuid);
    }

    private static void printCode(String msg) {
        System.out.println(localCode);
        System.out.println("插入了key为: " + msg + " 的验证码!");
    }

    public static User getCurrentUser(HttpServletRequest request) {
        return localUser.get(getToken(request));
    }

    public static Integer getCurrentUserId(HttpServletRequest request) {
        return getCurrentUser(request).getId();
    }

    private static void printUser(String token) {
        System.out.println("插入了key为: " + token + " 的用户!");
        System.out.println(localUser);
    }

    public static void removeCurrentUser(HttpServletRequest request) {
        if (getCurrentUser(request) != null) {
            localUser.remove(getToken(request));
        }
    }

    public static String getToken(HttpServletRequest request) {
        System.out.println("当前令牌为: " + request.getHeader("AUTH_TOKEN"));
        return request.getHeader("AUTH_TOKEN");
    }

    public static void setSignUser(String token, User user) {
        if (StringUtils.isEmpty(token)) {
            return;
        }
        localUser.put(token, user);
        printUser(token);
    }
}
